﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BillGuru
{
    public partial class FrmStockAdjust : Form
    {
        public FrmStockAdjust()
        {
            InitializeComponent();
        }

        private void FrmMoveStock_Load(object sender, EventArgs e)
        {
            stockAdjustmentReasonTableAdapter.Fill(billGuruDataSet.StockAdjustmentReason);
            productTableAdapter.Fill(billGuruDataSet.Product);

            stockAdjustmentTableAdapter.Adapter.RowUpdated += new System.Data.OleDb.OleDbRowUpdatedEventHandler(StockAdjustment_PKUpdate);
            stockAdjustmentTableAdapter.Adapter.RowUpdated += new System.Data.OleDb.OleDbRowUpdatedEventHandler(StockAdjustment_ProductUpdate);
        }

        private void StockAdjustment_PKUpdate(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e)
        {
            BillGuru.Persistence.SharedEventHandlerImpl.RetrieveKeyOnRowInsert(sender, e);
        }

        private void StockAdjustment_ProductUpdate(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e)
        {
            this.UpdateStock(sender, e);
        }

        private void UpdateStock(object sender, System.Data.OleDb.OleDbRowUpdatedEventArgs e)
        {
            float fStockAdded = 0f;
            float fStockReduced = 0f;


            if (e.StatementType == StatementType.Insert)
            {
                fStockAdded = (float)e.Row["StockAdded"];
                fStockReduced = (float)e.Row["StockReduced"];
            }
            else if (e.StatementType == StatementType.Update)
            {
                fStockAdded = ((float)e.Row["StockAdded"] - (float)e.Row["StockAdded", DataRowVersion.Original]);
                fStockReduced = ((float)e.Row["StockReduced"] - (float)e.Row["StockReduced", DataRowVersion.Original]);
            }
            else if (e.StatementType == StatementType.Delete)
            {
                fStockAdded = -(float) e.Row["StockAdded", DataRowVersion.Original];
                fStockReduced = -(float) e.Row["StockReduced", DataRowVersion.Original];
            }

            int pID;

            if (e.Row.HasVersion(DataRowVersion.Current))
                pID = (int)e.Row["ProductID-From", DataRowVersion.Current];
            else if (e.Row.HasVersion(DataRowVersion.Original))
                pID = (int)e.Row["ProductID-From", DataRowVersion.Original];
            else
                throw new InvalidOperationException();

            BillGuruDataSet.ProductRow[] productRows = null;

            productRows = (BillGuruDataSet.ProductRow[])billGuruDataSet.Product.Select("ID = " + pID);
            if (productRows == null || productRows.Count() != 1)
                throw new InvalidOperationException();

            BillGuruDataSet.ProductRow productRow = null;
            productRow = productRows[0];

            productRow.Stock -= (int)fStockReduced;
            this.productTableAdapter.Update(productRow);

            if (e.Row.HasVersion(DataRowVersion.Current))
                pID = (int)e.Row["ProductID-To", DataRowVersion.Current];
            else if (e.Row.HasVersion(DataRowVersion.Original))
                pID = (int)e.Row["ProductID-To", DataRowVersion.Original];
            else
                throw new InvalidOperationException();

            productRows = (BillGuruDataSet.ProductRow[])billGuruDataSet.Product.Select("ID = " + pID);
            if (productRows == null || productRows.Count() != 1)
                throw new InvalidOperationException();

            productRow = productRows[0];

            productRow.Stock += (int)fStockAdded;
            this.productTableAdapter.Update(productRow);
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == (Keys.Control | Keys.F))
            {
                this.tbFilter.Focus();
                this.tbFilter.SelectAll();
                return true;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void tbFilter_Validated(object sender, EventArgs e)
        {
            string sFilter = BillGuru.Utilities.DatabaseUtilities.createProductDescriptionFilter(tbFilter.Text);

            fromProductBindingSource.Filter = sFilter;
            toProductbindingSource.Filter = sFilter;
        }

        private void pbAdd_Click(object sender, EventArgs e)
        {
            BillGuruDataSet.StockAdjustmentRow row = (BillGuruDataSet.StockAdjustmentRow)billGuruDataSet.StockAdjustment.NewRow();
            row._ProductID_From = (int)this.cbFromProduct.SelectedValue;
            row._ProductID_To = (int)this.cbToProduct.SelectedValue;
            row.StockAdded = float.Parse(tbAdd.Text);
            row.StockReduced = float.Parse(tbReduce.Text);
            row.AdjustmentTime = DateTime.Now;
            row.ReasonID = (int)this.cbReason.SelectedValue;

            billGuruDataSet.StockAdjustment.AddStockAdjustmentRow(row);
        }

        private void pbSave_Click(object sender, EventArgs e)
        {
            stockAdjustmentTableAdapter.Update(billGuruDataSet.StockAdjustment);
        }

        private void pbLoad_Click(object sender, EventArgs e)
        {
            stockAdjustmentTableAdapter.Adapter.SelectCommand = new System.Data.OleDb.OleDbCommand();
            stockAdjustmentTableAdapter.Adapter.SelectCommand.CommandText = 
                "Select * from StockAdjustment where AdjustmentTime between #" + dtpFrom.Value.ToShortDateString() 
                + "# and #" + dtpTo.Value.ToShortDateString() + "#";
            stockAdjustmentTableAdapter.Adapter.SelectCommand.Connection = new System.Data.OleDb.OleDbConnection();
            stockAdjustmentTableAdapter.Adapter.SelectCommand.Connection.ConnectionString =
                 BillGuru.Properties.Settings.Default.BillGuruConnectionString;

            stockAdjustmentTableAdapter.Adapter.Fill(billGuruDataSet.StockAdjustment);
        }

        private void pbDone_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmStockAdjust_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (billGuruDataSet.HasChanges())
                BillGuru.UI.PermissionHandler.checkDataLoss(e);
        }
    }
}
